import dayjs from 'dayjs'
import isToday from 'dayjs/plugin/isToday'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
import { TimeType } from '@/components/DeepseekChat/types'
// 注册插件
dayjs.extend(isToday)
dayjs.extend(isSameOrBefore)
dayjs.extend(isSameOrAfter)
export function getCurrentDate(_date?: string | number | Date) {
  const date = _date ? new Date(_date) : new Date()
  const day = date.getDate()
  const month = date.getMonth() + 1
  const year = date.getFullYear()
  return `${year}-${month}-${day}`
}

type CallbackFunc<T extends unknown[]> = (...args: T) => void

export function debounce<T extends unknown[]>(
  func: CallbackFunc<T>,
  wait: number
): (...args: T) => void {
  let timeoutId: ReturnType<typeof setTimeout> | undefined

  return (...args: T) => {
    const later = () => {
      clearTimeout(timeoutId)
      func(...args)
    }

    clearTimeout(timeoutId)
    timeoutId = setTimeout(later, wait)
  }
}

// 完整的时间范围判断函数
export function getTimeRange(date: string | Date | number): TimeType {
  const targetDate = dayjs(date)
  const now = dayjs()

  if (targetDate.isToday()) {
    return TimeType.Day
  }

  if (targetDate.isSameOrAfter(now.subtract(7, 'day'), 'day')) {
    return TimeType.Week
  }

  if (targetDate.isSameOrAfter(now.subtract(1, 'month'), 'day')) {
    return TimeType.Month
  }

  if (targetDate.isSameOrAfter(now.subtract(1, 'year'), 'day')) {
    return TimeType.Year
  }

  return TimeType.Year
}

// 文件大小转换
export function fileSizeConversion(size: number) {
  if (size < 1024) {
    return `${size}B`
  }
  if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)}KB`
  }
  if (size < 1024 * 1024 * 1024) {
    return `${(size / 1024 / 1024).toFixed(2)}MB`
  }
  if (size < 1024 * 1024 * 1024 * 1024) {
    return `${(size / 1024 / 1024 / 1024).toFixed(2)}GB`
  }
  return `${(size / 1024 / 1024 / 1024 / 1024).toFixed(2)}TB`
}

// 根据后缀返回文件类型 比如docx、doc统一返回doc, xlsx、xls统一返回xls 已经别的文件类型
export function getFileType(fileName: string): string {
  const suffix = fileName.split('.').pop()
  if (suffix === 'docx' || suffix === 'doc') return 'word-filled'
  if (suffix === 'xlsx' || suffix === 'xls') return 'excel'
  if (suffix === 'pptx' || suffix === 'ppt') return 'ppt'
  if (suffix === 'pdf') return 'pdf'
  // if (suffix === 'txt') return 'txt'
  return 'txt'
}

// 根据string直接生成markdown文件，并且下载
export function generateMarkdown(content: string, fileName?: string) {
  content = content.replace(/<br>/g, '\n')
  const blob = new Blob([content], { type: 'text/markdown' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName ?? 'markdown.md'
  a.click()
  URL.revokeObjectURL(url)
}
